import os
from PIL import Image

def generate_thumbnail(image, size):
    t_w, t_h = size
    o_w, o_h = image.size
    
    rap = float(t_h) / t_w
    n_w = o_h / rap
    
    if n_w < o_w:
        n_h = o_h
        # Crop left right
        left = (o_w - n_w) / 2
        right = left + n_w
        top = 0
        bottom = n_h
    else:
        n_h = o_w * rap
        n_w = o_w
        # Crop top bottom
        left = 0
        right = n_w
        top = (o_h - n_h) / 2
        bottom = top + n_h
    
    thumbnail = image.copy()
    thumbnail = thumbnail.crop((int(left), int(top), int(right), int(bottom)))
    thumbnail = thumbnail.resize(size, Image.ANTIALIAS)
    
    return thumbnail
    
    #def _resize(self, path, image, max_size):
    #    max_w, max_h = max_size
    #    w, h = image.size
    #    
    #    rap = float(h) / w
    #    
    #    if w > max_w:
    #        w = max_w
    #        h = int(w * rap)
    #    
    #    if h > max_h:
    #        h = max_h
    #        w = int(h / rap)
    #    
    #    if w is not max_w or h is not max_h:
    #        resized = image.resize((w, h), Image.ANTIALIAS)
    #        resized.save(path)
    #
    #
    #def _save(self, name, content):
    #    name = super(ImageFileSystemStorage, self)._save(name, content)
    #    
    #    path = self.path(name)
    #    image = Image.open(open(path))
    #    
    #    self._resize(path, image, self.max_size)
    #    self._generate_thumbnail(path, image, self.thumb_size)
    #    
    #    return name

